package com.xiaoluo.matedata;

import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.util.Log;

/**
 * @ Created on: 2020/10/16
 * @Author: LEGION XiaoLuo
 * @ Description:
 */
public class MetaUtils {
    private static final String TAG = "MetaUtils";

    public static String getServiceMetaData(Context context, String pkg, String key) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(pkg, PackageManager.GET_SERVICES);
            Log.i(TAG, "getServiceMetaData: serviceInfo size = " + packageInfo.services.length);
            for (ServiceInfo service : packageInfo.services) {
                ComponentName cn = new ComponentName(pkg, service.name);
                ServiceInfo info = packageManager.getServiceInfo(cn, PackageManager.GET_META_DATA);
                if (info.metaData == null) {
                    Log.i(TAG, "getServiceMetaData: service name = " + service.name + " metaData is null");
                    continue;
                }
                String data = info.metaData.getString(key);
                Log.i(TAG, "getServiceMetaData: service name =" + service.name + "--data = " + data);
                if (data != null) {
                    return data;
                }
            }
            return null;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
